const requireEx=require('yi-require');
const lookup = require('yi-lookup');

const beforeSend = function (req,body,callback) {
    let goodsList = (body.data instanceof Array)?body.data:body.data.items;
    goodsList.forEach((item)=>{
        item["goods_store"]= item._id.toString()+'_'+item.storeId.toString();
    });
    let lookupList = [];
    lookupList.push({
        from:"warehouse",
        localField:"goods_store",
        foreignField:"goods_store",
        project:{createTime:0,lastModifyDate:0,pwd:0}
    }) ;

    lookup.lookup(req.mongo,goodsList,lookupList,(e,r)=> {
        goodsList = r;

        goodsList.forEach((item)=>{
            if(item["goods_store"] instanceof Object){
                item.quantity = item["goods_store"].quantity;
            }else{
                item.quantity = 0;
            }
            delete item["goods_store"];
        });
        callback(null, body);
    });
};


const middleware =  (req, res, next) =>{
    req.beforeSend = beforeSend;
    next();
};

module.exports = {
    open:true,
    description:'获取带库存数量商品列表',
    extend:"",
    middleware:middleware,
    handler: requireEx('yi-restful').r('goods',[])
};
